const handleDB=require("../db/handleDB")

//在cookie中设置一个csrf_token值(随机n位字符串)
function getRandomString(n){
    var str="";
    while(str.length<n){
        str+=Math.random().toString(36).substr(2);
    };
    return str.substr(str.length-n);
}

//设置CSRF防护
function csrfProtect(req, res, next){
    let method = req.method
    if(method=="GET"){
        let csrf_token = getRandomString(48);
        res.cookie('csrf_token', csrf_token);
        next() //执行跳转到下一个函数执行，即app.use(beforeReq,router)中的下一个
    }else if(method=="POST"){
        // 判断响应头中的x-csrftoken值，和cookies中的csrf_token进行对比
        console.log(req.headers["x-csrftoken"]);
        console.log(req.cookies["csrf_token"]);
        
        if((req.headers["x-csrftoken"] === req.cookies["csrf_token"])){
            console.log("csrf验证通过！");
            next()
        }else{
            res.send({errmsg:"csrf验证不通过！！"});
            return
        }
    }
}

//查询数据库用户是否存在
async function getUser(req, res){
    let user_id=req.session["user_id"];
    let result=[];
    if(user_id){
        result=await handleDB(res,"user","find","查询数据库出错",`user_id=${user_id}`)
    }
    return result
}

//获取用户信息函数
async function getUserInfo(req,res){
    let userInfo=await getUser(req,res);
    if(!userInfo[0]){
        res.redirect("/");
    }
    return userInfo
}

//获取店家用户信息函数
async function getUserindexInfo(req,res){
    let userInfo=await getUserInfo(req,res);
    if(userInfo[0].is_merchant!=1){
        res.redirect("/");
    }
    return userInfo
}

//404错误页面
async function abort404(req,res){
    let userInfo=await getUser(req,res);
    let number="";
        if(userInfo[0]){
            let indentCounts=await handleDB(res,"indent","sql","数据库查询出错",`select count(*) from indent where user_id=${userInfo[0].user_id} and is_order=0`);
            number=indentCounts[0]["count(*)"];
        }
        let data={
            user_info:userInfo[0]?{
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            number:number
        };
    res.render("404",data);
}
module.exports={
    csrfProtect,
    abort404,
    getUser,
    getUserInfo,
    getUserindexInfo
}
